<?php

namespace app\index\controller;

use app\admin\model\Dep_customer;
use app\index\model\Customer;
use think\Controller;
use app\extra\MSM\Message;
use think\Session;
use app\index\controller\Base;

class Register extends Base
{
    public function index()
    {
        return view('public/register');
    }


    public function getCode()
    {
        $tel = input('post.')['tel'];
        //var_dump($tel);die();
        $ex_time = 5;
        $tempID  = 1;
        $code = mt_rand(1000,9999);
        $mam_data = array($code, $ex_time);
        $message = new Message();
        $result = $message->sendTemplateSMS($tel, $mam_data, $tempID);
       if($result['status']){
          Session::set('code',$code);
          return json($result);
       }else{
          return json($result);
       }
    }

    public function reName()
    {
        $username = input('post.')['username'];
        $obj = model('customer')->where(function ($query) use ($username) {
            $query->where('username',$username);
        })->find();
        $arr = [];
        if($obj){
            $arr['status'] =  0;
            $arr['message'] = '用户名已存在！';
        }else{
            $arr['status'] =  1;
            $arr['message'] = '用户名有效！';
        }
        return json($arr);
    }

    public function reEmail()
    {
        $email = input('post.')['email'];
        $obj = model('customer')->where(function ($query) use ($email) {
            $query->where('email',$email);
        })->find();
        $arr = [];
        if($obj){
            $arr['status'] =  0;
            $arr['message'] = '用户名已存在！';
        }else{
            $arr['status'] =  1;
            $arr['message'] = '用户名有效！';
        }
        return json($arr);
    }

    public function reTel()
    {
        $tel = input('post.')['tel'];
        $obj = model('customer')->where(function ($query) use ($tel) {
            $query->where('tel',$tel);
        })->find();
        $arr = [];
        if($obj){
            $arr['status'] =  0;
            $arr['message'] = '用户名已存在！';
        }else{
            $arr['status'] =  1;
            $arr['message'] = '用户名有效！';
        }
        return json($arr);
    }

    public function add()
    {
        $info = input('post.');
        $code = $info['code'];
        if($code!=Session::get('code')){
            $this->error('验证码错误',url('index/register/index'));
        }
        $hash = password_hash($info['password'],PASSWORD_DEFAULT);

        $data = [];
        $data['username'] = $info['username'];
        $data['email'] = $info['email'];
        $data['tel'] = $info['tel'];
        $data['password'] = $hash;
        $result = Customer::create($data);
        if($result->id > 0){
            Dep_customer::create(['sex'=>1,'name'=>'未知','headimg'=>'head.jpg']);
            $this->success('恭喜你，注册成功！',url('index/login/index'));
        }else{
            $this->error('注册失败',url('index/register/index'));
        }
    }
    
}
